class Solution {
public:
    long long countSubarrays(vector<int>& nums, int k)
    {
        long long n = nums.size();
        long long m = ranges::max(nums);
        long long cnt = 0, ans = 0;
        long long left, right;
        for (left = 0, right = 0; right < n; right++)
        {
            if (nums[right] == m)
            {
                cnt++;
                if (cnt == k)
                {
                    while (left < right && nums[left] != m) ans += n - right, left++;
                    ans += n - right;
                    cnt--;
                    left++;
                }
            }
        }
        return ans;
    }
};